import Vue from 'vue'
import { findPendingMessageIndex } from './helpers'
import { getSelectedChatConversation } from './getters'

export const mutations = {
  clearConversations ($state) {
    Vue.set($state, 'conversations', [])
  },

  updateConversations ($state, conversations) {
    $state.conversations = conversations
  },

  setPreviousConversations ($state, { id, data }) {
    if (data.length) {
      const [chat] = $state.conversations.filter(c => c.id === id)
      data.forEach(message => {
        if (chat.messages.some(m => m.id === message.id) === false) {
          chat.messages.unshift(message)
        }
      })
    }
  },

  setCurrentConversationId ($state, { id }) {
    $state.currentConversationId = id
  },

  ADD_MESSAGE ({ conversations, currentConversationId }, message) {
    const { conversationId } = message
    const [chat] = getSelectedChatConversation({
      allConversations: conversations,
      selectedChatId: conversationId
    })
    if (!chat) return

    const pendingMessageIndex = findPendingMessageIndex(chat, message)

    if (pendingMessageIndex !== -1) {
      Vue.set(chat.messages, pendingMessageIndex, message)
    } else {
      chat.messages.push(message)
      chat.timestamp = message.createdAt
      if (currentConversationId === conversationId) {
        // window.bus.$emit(BUS_EVENTS.SCROLL_TO_MESSAGE)
      }
    }
  },

  ADD_CONVERSATION ({ conversations }, conversation) {
    conversations.push(conversation)
    // Vue.set(conversations, conversations)
  }
}
